<template>
  <div class="form-builder">
    <el-form
      :rules="rules"
      :ref="formConf.formModel"
      :size="formConf.size"
      :model="form"
      :label-position="formConf.labelPosition"
      :disabled="formConf.disabled"
      :validate-on-rule-change="false"
      :label-width="formConf.labelWidth + 'px'"
    >
      <template v-for="(element) in itemList" :key="element.id">
        <!-- 行组件处理（支持嵌套） -->
        <preview-row-item 
          v-if="element.compType === 'row'" 
          :model="element"
          @valChange="handlerValChange"
        >
          <el-col 
            v-for="column in element.columns" 
            :key="column.index" 
            v-bind="getColProps(column)"
          >
            <template v-for="col in column.list">
              <preview-item
                v-if="col.compType !== 'dynamicTable'"
                :key="col.id"
                :model="col"
                v-model="form[getFieldPath(element, col)]"
                @valChange="handlerValChange"
              />
              <fancy-dynamic-table
                v-else
                :key="'dynamic-' + col.id"
                :data="form[col.id]"
                :conf="col"
                @addRow="handlerAddRow"
                @deleteRow="handlerDeleteRow"
              >
                <template #item="{ rowScope, item }">
                  <fancy-dynamic-table-item
                    :model="item"
                    :parent="col"
                    v-model="rowScope.row[item.id]"
                    @valChange="(val) => handlerDynamicValChange(col.id, rowScope.$index, item.id, val)"
                  />
                </template>
              </fancy-dynamic-table>
            </template>
          </el-col>
        </preview-row-item>

        <fancy-dynamic-table
          v-else-if="element.compType === 'dynamicTable'"
          :key="'dynamic-' + element.id"
          :data="form[element.id]"
          :conf="element"
          @addRow="handlerAddRow"
          @deleteRow="handlerDeleteRow"
        >
          <template #item="{ rowScope, item }">
            <fancy-dynamic-table-item
              :model="item"
              v-model="rowScope.row[item.id]"
              @valChange="(val) => handlerDynamicValChange(element.id, rowScope.$index, item.id, val)"
            />
          </template>
        </fancy-dynamic-table>

        <fancy-edit-table
          v-else-if="element.compType === 'table'"
          :key="'table-' + element.id"
          :layoutArray="element.layoutArray"
          :tdStyle="element.tdStyle"
        >
          <template #default="{ td }">
            <template v-for="col in td.columns" :key="col.id">
              <preview-item
                :model="col"
                v-model="form[col.id]"
                @valChange="handlerValChange"
              />
            </template>
          </template>
        </fancy-edit-table>

        <el-col v-else class="drag-col-wrapper" :span="element.span">
          <preview-item
            :key="element.id"
            :model="element"
            v-model="form[element.id]"
            @valChange="handlerValChange"
          />
        </el-col>
      </template>
    </el-form>
    <el-divider />
    <div style="text-align: center">
      <el-button type="primary" @click="handlerSubForm">提交</el-button>
    </div>
  </div>
</template>

<script>
import previewItem from './previewItem';
import previewRowItem from './preview-row-item.vue';
import fancyDynamicTable from '../formDesigner/dynamic/fancyDynamicTable.vue';
import fancyDynamicTableItem from './dynamic/fancyDynamicTableItem';
import fancyEditTable from './table/fancyEditTable.vue';
import { datas, addRow, deleteRow, fillDatas } from './custom/formDraw';

export default {
  name: 'formBuilder',
  components: {
    previewItem,
    previewRowItem,
    fancyDynamicTable,
    fancyDynamicTableItem,
    fancyEditTable
  },
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    buildData: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    valChange: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      form: {},
      rules: {},
      itemList: [],
      isInitData: false,
      isBuildFormData: false,
      currentIndex: -1
    };
  },
  mounted() {
    this.$nextTick(this.initForm);
  },
  methods: {
    getColProps(column) {
      return column.responsive !== false ? {
        xs: column.xs || 24,
        sm: column.sm || column.span || 12,
        md: column.md || column.span || 8,
        lg: column.lg || column.span || 6,
        xl: column.xl || column.span || 4
      } : {
        span: column.span || 12
      };
    },
    initForm() {
      if (this.buildData && !this.isBuildFormData) {
        const buildData = JSON.parse(this.buildData);
        this.itemList = buildData.list;
        this.isBuildFormData = true;
      }

      if (!this.isInitData) {
        this.handlerInitDatas();
      }

      if (this.modelValue) {
        this.handlerFillDatas(JSON.parse(this.modelValue));
      }
    },

    // 获取字段路径（支持嵌套）
    getFieldPath(parent, child) {
      return parent.compType === 'row' ? `${parent.id}.${child.id}` : child.id;
    },

    // 处理嵌套值变化
    handleNestedValChange(path, value) {
      if (path.includes('.')) {
        const [parentId, childId] = path.split('.');
        this.$set(this.form[parentId], childId, value);
      } else {
        this.$set(this.form, path, value);
      }
      this.$emit('valChange', path, value);
    },
    handlerSubForm() {
      console.log(this.$refs[this.formConf.formModel]);
      
      this.$refs[this.formConf.formModel].validate((valid) => {
        if (valid) {
          this.$message.success('提交成功');
          this.$emit('submit', JSON.parse(JSON.stringify(this.form)));
        } else {
          this.$message.error('表单验证失败');
        }
      });
    },

    handlerValChange(key, origin) {
      this.form[key] = origin;
      //向父组件触发一个事件，父组件监听该事件
      this.$emit('valChange', key, origin);
    },

    handlerDynamicValChange(parentId, index, key, value) {
      if (!this.form[parentId]) {
        this.$set(this.form, parentId, []);
      }
      if (!this.form[parentId][index]) {
        this.$set(this.form[parentId], index, {});
      }
      this.$set(this.form[parentId][index], key, value);
      this.currentIndex = index;
    },

    async validate() {
      try {
        const valid = await this.$refs[this.formConf.formModel].validate();
        if (valid) {
          this.$message.success('验证成功');
          this.$emit('update:modelValue', JSON.stringify(this.form, null, 2));
          return true;
        }
      } catch (error) {
        this.$emit('update:modelValue', '');
        return false;
      }
    },

    // 外部方法引用
    handlerAddRow: addRow,
    handlerDeleteRow: deleteRow,
    handlerInitDatas: datas,
    handlerFillDatas: fillDatas
  },
  computed: {
    formConf() {
      if (this.buildData) {
        const buildData = JSON.parse(this.buildData);
        buildData.config.disabled = this.disabled;
        return buildData.config;
      }
      return {};
    }
  },
  watch: {
    modelValue(newVal) {
      if (newVal) {
        this.handlerFillDatas(JSON.parse(newVal));
      }
    },
    buildData: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          const buildData = JSON.parse(newVal);
          this.itemList = buildData.list;
          this.isBuildFormData = true;
          this.$nextTick(this.handlerInitDatas);
        }
      }
    }
  }
};
</script>

<style scoped>
.form-builder {
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.el-form-item {
  margin: 0 10px 18px;
}

.drag-col-wrapper {
  margin-bottom: 16px;
}

/* 嵌套行样式 */
.nested-row {
  border: 1px dashed #eee;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 16px;
}
</style>